package com.topcent.tioxyc.xxljob;

import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.topcent.tioxyc.constants.KeyConstant;
import com.topcent.tioxyc.pojo.Customer;
import com.topcent.tioxyc.pojo.DeliveryDocuments;
import com.topcent.tioxyc.pojo.DeliveryInfo;
import com.topcent.tioxyc.pojo.vo.WaiXiangJIaohuoVO;
import com.topcent.tioxyc.util.ApiClient;
import com.topcent.tioxyc.util.ConnmeUtils;
import com.topcent.tioxyc.util.PurchaseCommunity;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.Header;
import org.apache.http.message.BasicHeader;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author: weidian
 * @date: 2024/12/6 14:46
 * @Description: 信保客户推送消息
 */
@Component
@Slf4j
public class XinbaoXxlJob {

    @XxlJob("xinbaoXxlJob")
    public void xinbaoXxlJob() {
        Header[] headers = ConnmeUtils.createHeaders();
        Header[] headers1 = new Header[3];
        String auth = KeyConstant.sapName + ":" + KeyConstant.sapPass;
        String encodedAuth = Base64.getEncoder().encodeToString(auth.getBytes());
        String authHeader = "Basic " + encodedAuth;
        headers1[0] = new BasicHeader("Accept", "application/json");
        headers1[1] = new BasicHeader("Authorization", authHeader);
        headers1[2] = new BasicHeader("x-csrf-token", "Fetch");
        JSONObject entries1 =
                ApiClient.sendGetRequest("https://my200654-api.s4hana.sapcloud.cn/sap/opu/odata/sap/API_OUTBOUND_DELIVERY_SRV;v=0002/A_OutbDeliveryHeader", headers1, null);
        String d1 = entries1.getStr("d");
        JSONObject objects1 = JSONUtil.parseObj(d1);
        String results1 = objects1.getStr("results");
        JSONArray objectss1 = JSONUtil.parseArray(results1);
        List<WaiXiangJIaohuoVO> waiXiangJIaohuoVOList = JSONUtil.toList(objectss1, WaiXiangJIaohuoVO.class).stream()
                .filter(Objects::nonNull) // 过滤掉可能存在的 null 元素
                .collect(Collectors.collectingAndThen(
                        // 使用 TreeSet 保证元素的唯一性，根据字段 a 进行比较
                        Collectors.toCollection(() -> new java.util.TreeSet<>(Comparator.comparing(WaiXiangJIaohuoVO::getDeliveryDocument))),
                        ArrayList::new // 将 TreeSet 转换为 ArrayList
                ));

        Iterator<WaiXiangJIaohuoVO> iterator = waiXiangJIaohuoVOList.iterator();
        DateTime now = DateTime.now(); // 获取当前时间，只调用一次提高效率

        while (iterator.hasNext()) {
            WaiXiangJIaohuoVO waiXiangJIaohuoVO = iterator.next();

            // 检查字段是否不为空
            if (waiXiangJIaohuoVO.getYY1_YY1_lachangedateti_DLH() != null
                    && !waiXiangJIaohuoVO.getYY1_YY1_lachangedateti_DLH().isBlank()) {

                // 提取并转换时间戳
                long lct = Long.parseLong(ConnmeUtils.extractTimestamp(waiXiangJIaohuoVO.getYY1_YY1_lachangedateti_DLH()));
                LocalDateTime dateTime2 = ConnmeUtils.convertTimestampToLocalDateTime(lct);
                String formattedDateTime2 = ConnmeUtils.formatDateTime(dateTime2);
                DateTime dateTime4 = new DateTime(formattedDateTime2, DatePattern.NORM_DATETIME_FORMAT);

                // 设置解析后的时间对象回到 VO
                waiXiangJIaohuoVO.setYY1_YY1_lachangedateti_DLHs(dateTime4);

                // 判断日期是否是今天
                if (!DateUtil.isSameDay(dateTime4, now) || !"true".equals(waiXiangJIaohuoVO.getYY1_IF_Release_WMS_DLH())) {
                    iterator.remove();
                } else {
                //交货单_明细调用表
                Map<String, Object> cgdd = new HashMap<>();
                cgdd.put("app_id", "668f82dc2f5940fc022143d3");
                cgdd.put("entry_id", "6748024897dca2bc77466848");
                HashMap<String, String> communti = new HashMap<>();
                communti.put("_widget_1730770509313", waiXiangJIaohuoVO.getDeliveryDocument());
                List<WaiXiangJIaohuoVO> waiXiangJIaohuoVOS = PurchaseCommunity.queryBased(cgdd, headers, communti, WaiXiangJIaohuoVO.class);
                if (waiXiangJIaohuoVOS.isEmpty()) {
                    continue;
                }
                //客户编码
                String widget1732772568399 = waiXiangJIaohuoVOS.getFirst().get_widget_1732772568399();
                //客户主数据
                Map<String, Object> kehu = new HashMap<>();
                kehu.put("app_id", "66a6f42ff97af74b02d217df");
                kehu.put("entry_id", "66a6f443333584e2c128154f");
                HashMap<String, String> kehuc = new HashMap<>();
                kehuc.put("_widget_1722305048887", widget1732772568399);
                List<Customer> customers = PurchaseCommunity.queryBased(kehu, headers, kehuc, Customer.class);
                if (customers.isEmpty()) {
                    continue;
                }
                String widget1732245038716 = customers.getFirst().get_widget_1732245038716();
                if (!widget1732245038716.equals("是")) {
                    continue;
                }

                Map<String, Object> waixiang = new HashMap<>();
                waixiang.put("app_id", "668f82dc2f5940fc022143d3");
                waixiang.put("entry_id", "6752b495ab2359bc29a39a50");
                HashMap<String, String> jiaohuo = new HashMap<>();
                jiaohuo.put("_widget_1733473428479", waiXiangJIaohuoVO.getDeliveryDocument());
                List<DeliveryInfo> deliveryInfos = PurchaseCommunity.queryBased(waixiang, headers, jiaohuo, DeliveryInfo.class);
                if (deliveryInfos.isEmpty()) {
                    DeliveryInfo deliveryInfo = new DeliveryInfo();
                    deliveryInfo.set_widget_1733473428480(customers.getFirst().get_widget_1722217596682());
                    deliveryInfo.set_widget_1733473428479(waiXiangJIaohuoVO.getDeliveryDocument());
                    deliveryInfo.set_widget_1740636897665(waiXiangJIaohuoVOS.getFirst().get_widget_1732764831222().get("username"));
                    deliveryInfo.set_widget_1733473796643(waiXiangJIaohuoVO.getSalesOrganization());

                    Map<String, Object> parameterInster = new HashMap<>();
                    parameterInster.put("app_id", "668f82dc2f5940fc022143d3");
                    parameterInster.put("entry_id", "6752b495ab2359bc29a39a50");
                    parameterInster.put("is_start_trigger", "true");
                    deliveryInfo.set_id(null);
                    parameterInster.put("data", ConnmeUtils.convertEntityToMapNull(deliveryInfo));
                    String jsonSale = JSONUtil.toJsonStr(parameterInster);
                    log.info("外向交货单_是否允许交货--{}", jsonSale);
                    ApiClient.sendPostRequest(KeyConstant.Jian_URL + "/v5/app/entry/data/create", headers, jsonSale);
                }

                }


            } else {
                iterator.remove(); // 如果字段为空或 null，也移除
            }
        }

        log.info(String.valueOf(waiXiangJIaohuoVOList.size()));
    }
}
